package com.idea.easy.log.listener;

import com.idea.easy.log.model.ApiLog;
import com.idea.easy.log.provider.EasyLogInfoUtil;
import com.idea.easy.log.provider.EasyLogServerInfoProvider;
import com.idea.easy.log.event.ApiLogEvent;
import com.idea.easy.log.model.ApiLogModel;
import com.idea.easy.log.props.EasyLogProperties;
import com.idea.easy.log.provider.SpringAware;
import com.idea.easy.log.service.mp.IApiLogService;
import com.idea.easy.log.service.IEasyLogService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.Assert;



/**
 * @className: ApiLogListener
 * @description: ApiLog日志事件的监听
 * @author: salad
 * @date: 2022/6/9
 **/
@Slf4j
@AllArgsConstructor
public class ApiLogListener{

	private final EasyLogProperties properties;

	private final EasyLogServerInfoProvider serverInfoProvider;

	@Async
	@EventListener(ApiLogEvent.class)
	public void listener(ApiLogEvent event) {
		ApiLogModel apiLogModel = (ApiLogModel) event.getSource();
		//向实体类中增加额外的信息
		EasyLogInfoUtil.appendServerInfo(apiLogModel,serverInfoProvider,properties);
		//向IOC容器中寻找Bean
		IApiLogService apiLogService = SpringAware.getBean(IApiLogService.class);
		if (apiLogService != null){
			ApiLog apiLog = new ApiLog();
			BeanUtils.copyProperties(apiLogModel,apiLog);
			apiLog.setTitle(apiLogModel.getTitle());
			apiLogService.saveApiLog(apiLog);
		} else {
			IEasyLogService easyLogService = SpringAware.getBean(IEasyLogService.class);
			Assert.notNull(easyLogService,"easy-log: 为了存储日志数据,需要实现 IApiLogService 或者 IEasyLogService 接口");
			easyLogService.saveApiLog(apiLogModel);
		}

	}

}